import { baseUrl } from '@/constants';
import React, { useEffect, useRef, useState } from 'react';

const CameraCapture: React.FC<API.InterfaceInfo> = (props) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [capturedImage, setCapturedImage] = useState<string | null>(null);
  const [realRes, setRealRes] = useState();

  const setupCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }
    } catch (error) {
      console.error('获取摄像头失败：', error);
    }
  };
  useEffect(() => {
    setupCamera();
  }, []);
  const takeSnapshot = () => {
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');

      if (context) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        // 将 Data URL 转换为 Blob 对象
        canvas.toBlob(async (blob) => {
          // 创建一个 File 对象
          const file = new File([blob as BlobPart], 'snapshot.jpg', { type: 'image/jpeg' });

          // 创建 FormData 并附加文件
          const formData = new FormData();
          formData.append('multipartFile', file);
          const response = await fetch(`${baseUrl}${props.url}`, {
            method: 'POST',
            body: formData,
            headers: {
              token: localStorage.getItem('token') || '',
            },
          });
          response.json().then((res) => {
            setCapturedImage(res.url);
            setRealRes(res);
          });
          // 发送 FormData 到后端
        }, 'image/jpeg');
        // const imageURL = canvas.toDataURL('image/jpeg');
        // setCapturedImage(imageURL);
      }
    }
  };

  // const sendToBackend = async () => {
  //   if (capturedImage && !sending) {
  //     setSending(true);
  //     const formData = new FormData();
  //     formData.append('multipartFile', capturedImage);

  //     try {
  //       const response = await fetch('http://60.204.187.29:7529/api/opencv/camera', {
  //         method: 'POST',
  //         body: formData,
  //         headers: {
  //           token: localStorage.getItem('token') || '',
  //         },
  //       });

  //       // 处理后端响应
  //     } catch (error) {
  //       // 处理错误
  //     } finally {
  //       setSending(false);
  //       setCapturedImage(null);
  //     }
  //   }
  // };

  return (
    <div>
      <div style={{ fontSize: '20px' }}>{realRes && realRes.data}</div>
      <br />
      <div>
        <button onClick={takeSnapshot}>拍照</button>
      </div>
      <br />
      <div style={{ display: 'flex' }}>
        <video ref={videoRef} width="640" height="480" autoPlay />
        <canvas ref={canvasRef} style={{ display: 'none' }} />
        {capturedImage && <img src={capturedImage} alt="Captured" />}
      </div>
      {/* <button onClick={sendToBackend} disabled={!capturedImage || sending}>
        发送到后端
      </button> */}
    </div>
  );
};

export default CameraCapture;
